//
//  ByUIAddressVC.m
//  oc_knowledge
//
//  Created by mc on 17/1/12.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIAddressVC.h"

//Cell
#import "ByCellAddress.h"

//VC
#import "ByUIAddAddressVC.h"

//Api
#import "ByApiAddress.h"

@interface ByUIAddressVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSIndexPath *selectIndexPath;    //记录选择的cell

@end

@implementation ByUIAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"收货地址";
    [self addLeftBackBarButtonItem];
    
    [self initTableView];
    [self fetchData];

}
#pragma mark ---getter
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark ---获取数据
- (void)fetchData{
    ByModelAddress *model = [[ByModelAddress alloc] init];
    //测试数据
    model.uid = BY_USER.uid;
    model.s_id = BY_USER.s_id;
    [self performSelector:@selector(showLoading) withObject:nil afterDelay:0.2];
    [ByApiAddress addressQuery:model success:^(ByNetBaseResult *result) {
        if ([result.data isKindOfClass:[NSArray class]]) {
            for (ByModelAddress *model in result.data) {
                [self.dataArray addObject:model];
            }
            [self.tableView reloadData];
            [ByCoreToolAlert hideHud];
        }
        [ByCoreToolAlert hideHud];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}
/**用于延缓调用*/
- (void)showLoading{
    [ByCoreToolAlert showLoadind:@"加载中"];
}

#pragma mark ---创建视图
-(void)initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

}

#pragma mark ---UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count + 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /**添加地址*/
    if (indexPath.section == 0) {
        static NSString *indentier = @"addCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:indentier];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.textLabel.font = FONT(16);
            cell.textLabel.textColor = [UIColor blackColor];
            cell.detailTextLabel.textColor = [UIColor lightGrayColor];
            cell.detailTextLabel.font = FONT(14);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        UIImage *icon = [UIImage imageNamed:@"add"];
        CGSize imageSize = CGSizeMake(15, 15);
        UIGraphicsBeginImageContextWithOptions(imageSize, NO,0.0);         CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height);
        [icon drawInRect:imageRect];
        cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        cell.textLabel.text = @"新增收货地址";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"还可添加%ld个地址",10 - self.dataArray.count];
        return cell;
        
    }
    else{
        ByCellAddress *cell = [ByCellAddress cellWithTableView:tableView];
        ByModelAddress *model = self.dataArray[indexPath.section -1];
        cell.model = model;
        return cell;
        
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 50;
    }else
        return 80;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ByUIAddAddressVC *vc = [[ByUIAddAddressVC alloc] init];
    //设置回调
    [self setaddNewBlock:vc];
    [self setdeleteBlock:vc];
    [self setupdateBlock:vc];
    if (indexPath.section == 0) {
        if (self.dataArray.count == 10) {
            [ByCoreToolAlert showFailureWithText:@"最多只可以添加10个地址"];
            return;
        }
        vc.type = 0;
        [self by_normalPush:vc hasNavi:YES];
    }
    
    else{
        if (self.didSelectAddressBlock) {
            self.didSelectAddressBlock(self.dataArray[indexPath.section -1]);
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            
            self.selectIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section - 1];
            ByModelAddress *model = self.dataArray[indexPath.section -1];
            vc.type = 1;
            vc.alertModel = model;
            [self by_normalPush:vc hasNavi:YES];
        }
    }
}

/***左划删除*/
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
           return UITableViewCellEditingStyleNone;
    else {
           return UITableViewCellEditingStyleDelete;
    }
    
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {//title可自已定义
        ByModelAddress *model = self.dataArray[indexPath.row];
        model.uid = BY_USER.uid;
        model.s_id = BY_USER.s_id;
        [ByCoreToolAlert showLoadind:@"删除中..." hasMasker:YES];
        [ByApiAddress addressDelete:model success:^(ByNetBaseResult *result) {
            [ByCoreToolAlert showSuccessWithText:result.data];
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.tableView reloadData];
        } failure:^(ByNetBaseResult *result) {
            [ByCoreToolAlert showFailureWithText:result.msg];
        }];
    }];
    return @[deleteRoWAction];//最后返回这俩个RowAction 的数组
}

#pragma mark --相关操作
//更新地址
- (void)setupdateBlock:(ByUIAddAddressVC *)vc{
    vc.updateAddress = ^(ByModelAddress *model){
        //首先确认选择的model是否是默认地址
        ByModelAddress *selectModel = self.dataArray[self.selectIndexPath.section];
        //判断修改的地址是否是默认地址
        if (![selectModel.is_default isEqualToString:@"1"] && [model.is_default isEqualToString:@"1"]) {
            for (int i = 0; i < self.dataArray.count; i ++) {
                ByModelAddress *s_model = self.dataArray[i];
                if ([s_model.is_default isEqualToString:@"1"]) {
                    s_model.is_default = @"0";
                    [self.dataArray replaceObjectAtIndex:i withObject:s_model];
                    break;
                }
            }
        }
        
        [self.dataArray replaceObjectAtIndex:self.selectIndexPath.section withObject:model];
        [self.tableView reloadData];
    };
}

//新增地址
- (void)setaddNewBlock:(ByUIAddAddressVC *)vc{
    vc.addNewAddress = ^(ByModelAddress *model){
        //首先判断新增地址是否是默认地址
        if ([model.is_default isEqualToString:@"1"]) {
            for (int i = 0; i < self.dataArray.count; i ++) {
                ByModelAddress *s_model = self.dataArray[i];
                if ([s_model.is_default isEqualToString:@"1"]) {
                    s_model.is_default = @"0";
                    [self.dataArray replaceObjectAtIndex:i withObject:s_model];
                    break;
                }
            }
        }
        
        [self.dataArray insertObject:model atIndex:0];
        [self.tableView reloadData];

    };
}

//删除地址
- (void)setdeleteBlock:(ByUIAddAddressVC *)vc{
    vc.deleteAddress = ^(ByModelAddress *model){
        [self.dataArray removeObjectAtIndex:self.selectIndexPath.section];
        [self.tableView reloadData];
    };
}


@end
